package com.tzl.design_pattern.proxy_pattern;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author Zhilei Tang
 * @date Created in 2020/11/16 20:33
 */
public class JdkTravelAgency implements Travel, InvocationHandler {

  private Object target;

  public Object getInstance(Object target) { // 动态获取代理对象
    this.target = target;
    Class<?> clazz = target.getClass();
    return Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), this);
  }

  @Override
  public void buyTrainTicket() {}

  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    before();
    Object invoke = method.invoke(this.target, args);
    after();
    return invoke;
  }

  private void before() {
    System.out.println("付定金");
  }

  private void after() {
    System.out.println("付尾款");
  }
}
